using Catalog.Application.CatalogItems.Commands;
using Catalog.Application.CatalogItems.Interfaces;
using Catalog.Application.Interfaces;
using MediatR;

namespace Catalog.Application.CatalogItems.CommandHandlers;

public class ChangeCatalogItemPriceCommandHandler : IRequestHandler<ChangeCatalogItemPriceCommand, Unit>
{
    private readonly ICatalogItemRepository _catalogItemRepository;
    private readonly IUnitOfWork _unitOfWork;

    public ChangeCatalogItemPriceCommandHandler(ICatalogItemRepository catalogItemRepository, IUnitOfWork unitOfWork)
    {
        _catalogItemRepository = catalogItemRepository;
        _unitOfWork = unitOfWork;
    }


    public async Task<Unit> Handle(ChangeCatalogItemPriceCommand request, CancellationToken cancellationToken)
    {
        var catalogItem = await _catalogItemRepository.GetByIdAsync(request.id);
        if (catalogItem == null)
            throw new KeyNotFoundException("商品目录不存在！");

        catalogItem.ChangePrice(request.newPrice);
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Unit.Value;

    }
}